package com.yc.common.secure.domain;

import com.yc.common.secure.support.SecureAuthenticationProvider;
import com.yc.entity.StudentInfo;
import com.yc.entity.User;
import com.yc.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: model_project
 * @description:  Security 加载用户信息服务
 * @author: 作者 huchaojie
 * @create: 2023-06-11 14:46
 */
@Service
public class SecureUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username.length()==11){
            StudentInfo studentInfo = new StudentInfo(username, "STUDENT");
            return studentInfo;
        }else if (username.length()==10 && SecureAuthenticationProvider.status){
            StudentInfo studentInfo = new StudentInfo(username, "STUDENT");
            return studentInfo;
        }else {
            User user = userMapper.selectUserInfoAndRole(username);
            List<SimpleGrantedAuthority> authorityList = new ArrayList<>();//权限集合
            SimpleGrantedAuthority authority;//权限对象
            if (StringUtils.isNotBlank(user.getRolecode()) && StringUtils.isNotEmpty(user.getRolecode())) {
                String[] split = user.getRolecode().split(",");
                if (split.length>0) {
                    for (String roleCode : split) {
                        if (StringUtils.isNotBlank(roleCode) && StringUtils.isNotEmpty(roleCode)) {
                            authority = new SimpleGrantedAuthority(roleCode);
                            authorityList.add(authority);
                        }
                    }
                }
            }
            user.setAuthorities(authorityList);
            return user;
        }

    }

}
